package models

import (
	"fmt"
	"gitee.com/lzqysoft/ims/libs/cache"
	"gitee.com/lzqysoft/ims/libs/encrypt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
	"time"
	//"reflect"
	"errors"
	"gitee.com/lzqysoft/ims/libs/params"
	"reflect"
)

type Resource2 struct {
	Id        string    `orm:"column(id);pk"`
	Pid       string    `orm:"column(pid);null"`
	Type      int       `orm:"column(type)"`
	Seq       int       `orm:"column(seq)"`
	Remark    string    `orm:"column(remark);null"`
	Status    int       `orm:"column(status)"`
	Isdelete  int       `orm:"column(isdelete);null"`
	Ctime     time.Time `orm:"column(ctime);type(timestamp with time zone);null"`
	Creater   string    `orm:"column(creater)"`
	CreaterId string    `orm:"column(creater_id);null"`
	Utime     time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater   string    `orm:"column(updater)"`
	UpdaterId string    `orm:"column(updater_id);null"`
	Hiden     bool      `orm:"column(hiden);null"`
	Path      string    `orm:"column(path);null"`
	Url       string    `orm:"column(url);null"`
	Name      string    `orm:"column(name);null"`
	Icon      string    `orm:"column(icon);null"`
	Event     string    `orm:"column(event);null"`
}

func (m *Resource2) TableName() string {
	return "sys_resource2"
}

func init() {
	orm.RegisterModel(new(Resource2))
}

func (m Resource2) GetSorter() int {
	return m.Seq
}

// AddResource insert a new Resource into database and returns
// last inserted Id on success.
func AddResource2(m *Resource2) (id int64, err error) {
	o := orm.NewOrm()
	o.Begin()
	id, err = o.Insert(m)
	if err != nil {
		beego.Debug(err)
		o.Rollback()
		return
	}
	// 如果当前添加的资源是页面，  就添加基础的的操作按钮权限
	if m.Type == 2 {
		err = addChildOperateLabelSource(m.Id, m.Name, o)
		if err != nil {
			beego.Debug(err)
			o.Rollback()
		}
	}
	o.Commit()
	return
}

// GetResourceById retrieves Resource by Id. Returns error if
// Id doesn't exist
func GetResource2ById(id string) (v *Resource2, err error) {
	o := orm.NewOrm()
	v = &Resource2{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

//根据Pid 获取Resource
func GetResource2ByPid(pid string) ([]Resource2, error) {
	o := orm.NewOrm()
	var rList []Resource2
	if _, err := o.QueryTable(new(Resource2)).Filter("Isdelete", 0).Filter("pid", pid).All(&rList); err == nil {
		return rList, nil
	} else {
		return nil, err
	}
}

// GetAllResource retrieves all Resource matches certain condition. Returns empty list if
// no records exist
func GetAllResource2(query map[string]string, fields []string, sortby []string, order []string,
	offset int, limit int) (ml []interface{}, count int, err error) {
	o := orm.NewOrm()
	num, err := o.QueryTable(new(Resource2)).Filter("Status", 1).Filter("Isdelete", 0).Count()
	if err != nil {
		return
	}
	count = int(num)
	qs := o.QueryTable(new(Resource2))
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []orm.Params
	qs = qs.OrderBy(sortFields...).Filter("status", 1).Filter("isdelete", 0).OrderBy("ctime", "seq")
	if _, err = qs.Limit(limit, offset).Values(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				r, err := GetResource2ById(v["Pid"].(string))
				if err == nil && len(r.Name) > 0 {
					v["Pname"] = r.Name
				} else {
					v["Pname"] = "根目录"
				}
				v["Tname"] = params.GetResouce2Type(int(v["Type"].(int64)))
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, count, nil
	}
	return
}

// UpdateResource updates Resource by Id and returns error if
// the record to be updated doesn't exist
func UpdateResource2ById(m *Resource2) (err error) {
	o := orm.NewOrm()
	v := Resource2{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteResource deletes Resource by Id and returns error if
// the record to be deleted doesn't exist
func DeleteResource2(id string) (err error) {
	o := orm.NewOrm()
	v := Resource2{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Resource2{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

//SoftDeleteResource 软删除资源数据
//Param id int64
//Param uname string
//return error
func SoftDeleteResource2(id string, uname string) (err error) {
	o := orm.NewOrm()
	v := Resource2{Id: id}
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

//获取所有的资源列表
func GetAllResource2List(rtype int64) (count int64, resources []orm.Params) {
	cid := "GetAllResource2List.rtype." + strconv.Itoa(int(rtype))
	cid2 := "GetResource2ByRoleId.countd.rtype." + strconv.Itoa(int(rtype))
	err := cache.GetCache(cid, &resources)
	err2 := cache.GetCache(cid2, &count)
	if err != nil || err2 != nil {
		o := orm.NewOrm()
		// resource := Resource{}
		qs := o.QueryTable(new(Resource2)).Filter("Status", 1).Filter("Isdelete", 0)
		qs = qs.Limit(-1).OrderBy("Pid", "Seq")
		if rtype > 0 {
			qs = qs.Filter("type", 1)
		}
		count, err = qs.Values(&resources)
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		cache.SetCache(cid, resources, cache_expire)
		cache.SetCache(cid2, count, cache_expire)
	}

	return count, resources
}

//根据角色获取资源列表
func GetResource2ByRoleId(id string, rtype int64) ([]orm.Params, int64) {
	cid := "GetResource2ByRoleId.id." + id + "." + strconv.Itoa(int(rtype))
	cid2 := "GetResource2ByRoleId.countd." + id + "." + strconv.Itoa(int(rtype))
	var resources []orm.Params
	var count int64
	// tree := new(ResTree)
	beego.Debug(rtype)
	err := cache.GetCache(cid2, &count)
	err = cache.GetCache(cid, &resources)
	if err != nil {
		o := orm.NewOrm()
		resource := new(Resource2)
		var reslist orm.ParamsList
		count, _ = o.QueryTable("sys_role_sys_resources").Filter("sys_role_id", id).Limit(-1).ValuesFlat(&reslist, "sys_resource_id")
		qs := o.QueryTable(resource).Filter("id__in", reslist).Filter("isdelete", 0).Filter("Status", 1).OrderBy("Pid", "Seq").Limit(-1)
		if rtype > 0 {
			qs = qs.Filter("type", 1)
		}
		count, _ = qs.Values(&resources)
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		cache.SetCache(cid, resources, cache_expire)
		cache.SetCache(cid2, count, cache_expire)
	}
	return resources, count
}

//获取资源的子资源
func GetRes2SubTree(pid string, status int64) ([]orm.Params, error) {
	o := orm.NewOrm()
	resource := new(Resource2)
	var resources []orm.Params
	_, err := o.QueryTable(resource).Filter("Pid", pid).Filter("status", status).Filter("isdelete", 0).OrderBy("Pid", "Seq").Values(&resources)
	if err != nil {
		return resources, err
	}
	return resources, nil
}

//GetResMenu 获取目录根资源
func GetRes2Menu() (resources []Resource, err error) {
	o := orm.NewOrm()
	resource := new(Resource2)
	qs := o.QueryTable(resource).Filter("type", 1).Filter("pid", 0).Filter("status", 1)
	_, err = qs.Filter("isdelete", 0).OrderBy("Pid", "Seq").Limit(-1).All(&resources)

	return
}

//GetResMenuNode获取目录根资源
func GetRes2MenuNode() (resources []Resource, err error) {
	o := orm.NewOrm()
	resource := new(Resource2)
	qs := o.QueryTable(resource).Filter("type", 1).Exclude("pid", 0).Filter("status", 1)
	_, err = qs.Filter("isdelete", 0).OrderBy("Pid", "Seq").Limit(-1).All(&resources)
	return
}

//GetResIDByRoleId 根据角色获取资源列表id
func GetRes2IdByRoleId(id string) ([]string, error) {
	cid := "GetRes2IdByRoleId.id." + id
	var resIds []string
	err := cache.GetCache(cid, &resIds)
	if err != nil {
		o := orm.NewOrm()
		var reslist orm.ParamsList
		_, err = o.QueryTable("sys_role_sys_resources").Filter("sys_role_id", id).Limit(-1).ValuesFlat(&reslist, "sys_resource_id")
		if err != nil {
			return nil, err
		}
		resIds = nil
		for _, v := range reslist {
			resIds = append(resIds, v.(string))
		}
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		cache.SetCache(cid, resIds, cache_expire)
	}
	return resIds, err
}

//AddResOpe 增加资源操作
func AddRes2Ope() (err error) {
	res, _ := GetResMenuNode()
	for _, k := range res {
		var nr, nr1, nr2, nr3, nr4, nr5 Resource2
		nr.Id = encrypt.GetGuid()
		nr.Pid = k.Id
		nr.Type = 3
		nr.Seq = 100
		nr.Ctime = time.Now()
		nr.Creater = "admin"
		nr.Updater = "admin"
		nr.Utime = time.Now()
		nr.Name = k.Name + "-查看"

		nr1.Id = encrypt.GetGuid()
		nr1.Pid = k.Id
		nr1.Type = 3
		nr1.Seq = 101
		nr1.Ctime = time.Now()
		nr1.Creater = "admin"
		nr1.Updater = "admin"
		nr1.Utime = time.Now()
		nr1.Name = k.Name + "-增加"

		nr2.Id = encrypt.GetGuid()
		nr2.Pid = k.Id
		nr2.Type = 3
		nr2.Seq = 102
		nr2.Ctime = time.Now()
		nr2.Creater = "admin"
		nr2.Updater = "admin"
		nr2.Utime = time.Now()
		nr2.Name = k.Name + "-删除"

		nr3.Id = encrypt.GetGuid()
		nr3.Pid = k.Id
		nr3.Type = 3
		nr3.Seq = 103
		nr3.Ctime = time.Now()
		nr3.Creater = "admin"
		nr3.Updater = "admin"
		nr3.Utime = time.Now()
		nr3.Name = k.Name + "-修改"

		nr4.Id = encrypt.GetGuid()
		nr4.Pid = k.Id
		nr4.Type = 3
		nr4.Seq = 104
		nr4.Ctime = time.Now()
		nr4.Creater = "admin"
		nr4.Updater = "admin"
		nr4.Utime = time.Now()
		nr4.Name = k.Name + "-分配"

		nr5.Id = encrypt.GetGuid()
		nr5.Pid = k.Id
		nr5.Type = 3
		nr5.Seq = 105
		nr5.Ctime = time.Now()
		nr5.Creater = "admin"
		nr5.Updater = "admin"
		nr5.Utime = time.Now()
		nr5.Name = k.Name + "-审批"
		AddResource2(&nr)
		AddResource2(&nr1)
		AddResource2(&nr2)
		AddResource2(&nr3)
		AddResource2(&nr4)
		AddResource2(&nr5)
	}
	return
}

func addChildOperateLabelSource(parentId, parentName string, o orm.Ormer) error {
	var nr, nr1, nr2, nr3, nr4, nr5 Resource2
	nr.Id = encrypt.GetGuid()
	nr.Pid = parentId
	nr.Type = 3
	nr.Status = 1
	nr.Seq = 100
	nr.Ctime = time.Now()
	nr.Creater = "admin"
	nr.Updater = "admin"
	nr.Utime = time.Now()
	nr.Name = parentName + "-查看"
	nr.Url = "/query"
	nr.Icon = "md-search"
	nr.Event = "query"

	nr1.Id = encrypt.GetGuid()
	nr1.Pid = parentId
	nr1.Type = 3
	nr1.Seq = 101
	nr1.Status = 1
	nr1.Ctime = time.Now()
	nr1.Creater = "admin"
	nr1.Updater = "admin"
	nr1.Utime = time.Now()
	nr1.Name = parentName + "-增加"
	nr1.Url = "/add"
	nr1.Icon = "md-add"
	nr1.Event = "add"

	nr2.Id = encrypt.GetGuid()
	nr2.Pid = parentId
	nr2.Type = 3
	nr2.Seq = 102
	nr2.Status = 1
	nr2.Ctime = time.Now()
	nr2.Creater = "admin"
	nr2.Updater = "admin"
	nr2.Utime = time.Now()
	nr2.Name = parentName + "-删除"
	nr2.Url = "/delete"
	nr2.Icon = "ios-trash"
	nr2.Event = "delete"

	nr3.Id = encrypt.GetGuid()
	nr3.Pid = parentId
	nr3.Type = 3
	nr3.Seq = 103
	nr3.Status = 1
	nr3.Ctime = time.Now()
	nr3.Creater = "admin"
	nr3.Updater = "admin"
	nr3.Utime = time.Now()
	nr3.Name = parentName + "-修改"
	nr3.Url = "/update"
	nr3.Icon = "ios-card"
	nr3.Event = "update"

	nr4.Id = encrypt.GetGuid()
	nr4.Pid = parentId
	nr4.Type = 3
	nr4.Seq = 104
	nr4.Status = 1
	nr4.Ctime = time.Now()
	nr4.Creater = "admin"
	nr4.Updater = "admin"
	nr4.Utime = time.Now()
	nr4.Name = parentName + "-分配"
	nr4.Url = "/dispatch"
	nr4.Icon = "md-git-branch"
	nr4.Event = "dispatch"

	nr5.Id = encrypt.GetGuid()
	nr5.Pid = parentId
	nr5.Type = 3
	nr5.Seq = 105
	nr5.Status = 1
	nr5.Ctime = time.Now()
	nr5.Creater = "admin"
	nr5.Updater = "admin"
	nr5.Utime = time.Now()
	nr5.Name = parentName + "-审批"
	nr5.Url = "/assign"
	nr5.Icon = "md-git-branch"
	nr5.Event = "assign"

	_, err := o.InsertMulti(6, []Resource2{nr, nr1, nr2, nr3, nr4, nr5})
	return err
}

//Desc 获取资源的树
//Param pid int64 父资源id，一般取0为根路径
//Param status int64 状态
//return tree []map[string]interface{}, err error
func GetRes2Tree(pid string, status int64) (tree []map[string]interface{}, err error) {
	//	var resources []orm.Params
	resources, err := GetResSubTree(pid, status)
	res := make([]map[string]interface{}, 100)
	if err != nil {
		//		for k, v := range resources {
		//			tree[k] = v
		return
		//		}
	} else {
		for k, v := range resources {
			children, er := GetRes2Tree(v["Id"].(string), status)
			v["children"] = children
			res[k] = v
			tree = res
			if er != nil {
				err = er
				return
			}
		}
		return
	}

}

//用户授权角色
func AddRoleResource2(roleid string, resid string) (int64, error) {
	o := orm.NewOrm()
	role := Role{Id: roleid}
	res := Resource{Id: resid}
	m2m := o.QueryM2M(&res, "Role")
	num, err := m2m.Add(&role)
	cid := "GetAllResByRoleId.id." + roleid
	cache.DelCache(cid)
	return num, err
}

// QueryAllResource2ByRole 根据角色查询资源
func QueryAllResource2ByRole(roldId string) ([]Resource2, error) {
	o := orm.NewOrm()
	var l []Resource2
	var err error
	if roldId == "1" {
		// 超级管理员，具有所有权限, ji即查询所有资源
		_, err = o.QueryTable(new(Resource2)).Filter("Status", 1).Filter("Isdelete", 0).Limit(-1).All(&l)
		return l, err
	} else {
		// 其它管理员， 按授权查询
	}
	return nil, nil
}

// generateRes2Tree
func generateRes2Tree(l []Resource2) ([]Res2Tree, error) {

	return nil, nil
}

// generateRes2List 经过排序和处理的Resouce2切片
func generateRes2List(l []Resource2) []Resource2 {
	//var res []Resource2

	return nil
}

// findResource2ByType 根据资源类型查找
func findResource2ByType(rtype int, l []Resource2) []Resource2 {
	var res []Resource2
	for k, _ := range l {
		if l[k].Type == rtype {
			res = append(res, l[k])
		}
	}
	if len(res) > 0 {
		bubbleSort(res)
	}
	return res
}

// 权限模型模型
type Res2Tree struct {
	Id       string     `json:"id"`
	Name     string     `json:"name"`
	Icon     string     `json:"icon"`
	Type     int        `json:"type"`
	Seq      int        `json:"seq"`
	Url      string     `json:"url"`
	Path     string     `json:"path"`
	Event    string     `json:"event"`
	Hidden   bool       `json:"hidden"`
	Children []Res2Tree `json:"children"`
}

// BubbleSort 冒泡排序
func bubbleSort(li []Resource2) {
	for i := 0; i < len(li)-1; i++ {
		exchange := false
		for j := 0; j < len(li)-i-1; j++ {
			if li[j].Seq > li[j+1].Seq {
				li[j], li[j+1] = li[j+1], li[j]
				exchange = true
			}
		}
		if !exchange {
			return
		}
	}
}

func GetModules(role *Role) (res []orm.Params, err error) {
	if role.Id == "1" {
		// 超级管理员
		res, err = getAllModules()
	} else {
		// 其它
		res, err = getModulesByRole(role.Id)
	}
	return
}

// 获取模块
func getAllModules() ([]orm.Params, error) {
	var res []orm.Params
	o := orm.NewOrm()
	_, err := o.QueryTable(new(Resource2)).Filter("type", 0).Filter("pid", "0").Filter("status", 1).
		Filter("isdelete", 0).OrderBy("Seq").
		Values(&res, "Id", "Seq", "Name", "Icon")
	return res, err
}
func getModulesByRole(roleId string) ([]orm.Params, error) {
	o := orm.NewOrm()
	//o.Begin()
	var ids orm.ParamsList
	_, err := o.QueryTable("sys_role_sys_resources").Filter("sys_role_id", roleId).
		ValuesFlat(&ids, "sys_resource_id")
	if err != nil {
		beego.Debug(err)
		//o.Rollback()
		return nil, err
	}
	var l []orm.Params
	_, err = o.QueryTable(new(Resource2)).Filter("Id__in", ids).Filter("type", 0).Filter("Isdelete", 0).
		Filter("Status", 1).OrderBy("Seq").
		Values(&l, "Id", "Seq", "Name", "Icon")
	if err != nil {
		beego.Debug(err)
		//o.Rollback()
		return nil, err
	}
	//sql := `
	//SELECT "id" "Id", "seq" "Seq"", "name" "Name"", "icon" "Icon"" FROM sys_resource2 WHERE "id" in (
	//	SELECT sys_resource_id FROM sys_role_sys_resources WHERE "sys_role_id"= ?
	//)
	//AND isdelete=0 AND status = 1 AND type = 0 ;
	//`
	//var res []orm.Params
	//_, err := o.Raw(sql,roleId).Values(&res, "Id", "Seq", "Name", "Icon")
	//if err != nil {
	//	o.Rollback()
	//}
	return l, err
}
func GetMenusByRole(role *Role, resource *Resource2) (Res2Tree, error) {
	if role.Id == "1" {
		beego.Debug(role)
		// 超级管理员
		res, err := getAllResouce2()
		var tree Res2Tree
		tree.Id = resource.Id
		tree.Name = resource.Name
		tree.Icon = resource.Icon
		tree.Type = resource.Type
		tree.Seq = resource.Seq
		tree.Path = resource.Path
		tree.Hidden = resource.Hiden
		generateMenus(&tree, res, resource.Id)
		//beego.Debug(tree)
		return tree, err
	} else {
		beego.Debug(resource.Id)
		var tree Res2Tree
		tree.Id = resource.Id
		tree.Name = resource.Name
		tree.Icon = resource.Icon
		tree.Type = resource.Type
		tree.Seq = resource.Seq
		tree.Path = resource.Path
		tree.Hidden = resource.Hiden
		res, err := getResouce2ByRole(role.Id)
		//beego.Debug(res)
		if err != nil {
			beego.Debug(err)
			return Res2Tree{}, err
		}
		generateMenus(&tree, res, resource.Id)
		//beego.Debug(tree)
		return tree, err
	}
	return Res2Tree{}, nil
}

func getAllResouce2() ([]Resource2, error) {
	o := orm.NewOrm()
	var res2 []Resource2
	_, err := o.QueryTable(new(Resource2)).Filter("status", 1).Filter("isdelete", 0).OrderBy("seq").All(&res2)
	return res2, err
}
func getResouce2ByRole(roleId string) ([]Resource2, error) {
	o := orm.NewOrm()
	var res2 []Resource2
	//o.Begin()
	var ids orm.ParamsList
	_, err := o.QueryTable("sys_role_sys_resources").Filter("sys_role_id", roleId).
		ValuesFlat(&ids, "sys_resource_id")
	if err != nil {
		beego.Debug(err)
		//o.Rollback()
		return nil, err
	}
	_, err = o.QueryTable(new(Resource2)).Filter("Id__in", ids).Filter("Isdelete", 0).
		Filter("Status", 1).OrderBy("Seq").
		All(&res2)
	if err != nil {
		beego.Debug(err)
		//o.Rollback()
		return nil, err
	}
	return res2, nil
}
func generateMenus(tree *Res2Tree, list []Resource2, pid string) {
	//beego.Debug(list)
	for _, v := range list {
		if v.Pid == pid {
			//beego.Debug(v.Pid,pid)
			node := Res2Tree{}
			node.Id = v.Id
			node.Name = v.Name
			node.Icon = v.Icon
			node.Type = v.Type
			node.Seq = v.Seq
			node.Path = v.Path
			node.Hidden = v.Hiden
			generateMenus(&node, list, v.Id)
			tree.Children = append(tree.Children, node)
		}
	}
}

func GetOperateLabels(role *Role, name string) ([]orm.Params, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Resource2))
	if role.Id == "1" {
		// 超级管理员， 所有权限
		var res []orm.Params
		_, err := qs.Filter("name__contains", name).Filter("isdelete", 0).Filter("type", 3).
			OrderBy("seq").Values(&res)
		return res, err
	} else {
		var ids orm.ParamsList
		_, err := o.QueryTable("sys_role_sys_resources").Filter("sys_role_id", role.Id).
			ValuesFlat(&ids, "sys_resource_id")
		if err != nil {
			beego.Debug(err)
			//o.Rollback()
			return nil, err
		}
		var res []orm.Params
		_, err = o.QueryTable(new(Resource2)).Filter("Id__in", ids).Filter("Isdelete", 0).
			Filter("name__contains", name).Filter("type", 3).
			Filter("Status", 1).OrderBy("Seq").
			Values(&res)
		return res, err
	}
	return nil, nil
}

// MultSoftDeleteResouce2 批量软删除Resource2
func MultSoftDeleteResouce2(l []Resource2) error {
	o := orm.NewOrm()
	var ids []string
	for _, val := range l {
		ids = append(ids, val.Id)
	}
	_, err := o.QueryTable(new(Resource2)).Filter("id__in", ids).Update(orm.Params{
		"isdelete": 1,
		"status":   0,
	})
	return err
}
